package com.guapi.controller;

import cn.hutool.core.util.StrUtil;
import com.guapi.annotation.SelfController;
import com.guapi.dao.ResponseData;
import com.guapi.dao.SystemJob;
import com.guapi.dao.User;
import com.guapi.exception.SelfException;
import com.guapi.schedule.CronTaskRegister;
import com.guapi.service.JobService;
import com.guapi.thread.ScheduleThread;
import com.guapi.util.request.SelfRequest;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@SelfController
@RequestMapping("/job")
@ResponseBody
public class JobController extends BaseController<SystemJob> {
    @Autowired
    private JobService jobService;

    @Autowired
    private CronTaskRegister cronTaskRegister;

    @RequestMapping("/list")
    public ResponseData getRoleList(HttpServletRequest request, @RequestBody Map data) {
        responseData = new ResponseData();
        List<SystemJob> jobList;
        String searchBean = "";
        String searchMethod = "";
        String searchCron = "";
        Map searchStr = (Map) data.get("searchStr");
        if (searchStr != null) {
            searchBean = (String) searchStr.get("bean");
            searchMethod = (String) searchStr.get("method");
            searchCron = (String) searchStr.get("cron");
        }
        startPage(data);

        if (StrUtil.isAllEmpty(searchBean, searchCron, searchMethod)) {
            jobList = jobService.list();
        } else {
            SystemJob systemJob = new SystemJob();
            if (StrUtil.isNotEmpty(searchBean)) {
                systemJob.setBeanName(searchBean);
            }
            if (StrUtil.isNotEmpty(searchMethod)) {
                systemJob.setMethodName(searchMethod);
            }
            if (StrUtil.isNotEmpty(searchCron)) {
                systemJob.setCronExpression(searchCron);
            }
            jobList = jobService.getByFuzzy(systemJob);
        }
        responseData.setRows(jobList);
        responseData.setSuccess(true);
        return responseData;
    }

    @RequestMapping("/save/{judgeEdit}")
    public ResponseData saveOrUpdateJob(HttpServletRequest request, @RequestBody SystemJob job, @PathVariable("judgeEdit") boolean judgeEdit) {
        try {
            SelfRequest selfRequest = createRequest(request);
            responseData = new ResponseData();
            User loginUser = getLoginUser();
            //判断新增的job状态
            ScheduleThread scheduleThread = new ScheduleThread(job.getBeanName(), job.getMethodName(), job.getMethodParams());
            if (job.judgeIsEnable()) {
                cronTaskRegister.addCronTask(scheduleThread, job.getCronExpression());
            } else {
                cronTaskRegister.removeRunTask(scheduleThread);
            }
            if (judgeEdit) {
                //判断是编辑
                job.setUpdateBy(String.valueOf(loginUser.getId()));
                jobService.updateById(job);
            } else {
                //判断是新增
                //判断是否重复插入
                List<SystemJob> databaseList = jobService.list();
                databaseList.forEach(database -> {
                    if (job.equals(database)) {
                        throw new SelfException("不可重复添加定时任务,请检查bean名称,方法名称,Cron参数");
                    }
                });
                job.setCreateBy(String.valueOf(loginUser.getId()));
                jobService.save(job);

            }
            responseData.setData("job", job);
            responseData.setSuccess(true);
            return responseData;
        } catch (NoSuchBeanDefinitionException e) {
            e.printStackTrace();
            throw new SelfException("找不到已存在的bean!");
        }

    }

    @RequestMapping("/delete")
    public ResponseData deleteJob(HttpServletRequest request, @RequestBody SystemJob job) {
        responseData = new ResponseData();
        jobService.deleteById(job);
        responseData.setSuccess(true);
        return responseData;
    }
}
